import * as API from './api.js';
import request from './request.js';

// 记录添加/修改中的状态
let status = '';
let currentId = -1;
let layerId = -1;
let data = []; // 记录的数据

// 点击修改按钮弹出弹出层
function onEdit (id) {
    status = 'edit';
    currentId = id;
    // 返显input中的内容
    const current = data.find(item => item.id === id);
    $('#name').val(current.cate_name);
    $('#alias').val(current.cate_alias);

    layerId = layer.open({
        type: 1,
        title: '修改文章分类',
        content: $('.popup'),
        cancel () {
            setTimeout(() => {
                $('.popup').hide();
            });
        },
    });
}

// 修改确认
async function onEditOk (params) {
    const res = await request({
        url: API.ARTICLE_EDIT,
        method: 'put',
        data: {
            id: currentId,
            ...params,
        },
    });

    // layer.msg(res.data.message);
}

// 添加确认
async function onAddOk (params) {
    const res = await request({
        url: API.ARTICLE_ADD,
        method: 'post',
        data: params,
    });
    // layer.msg(res.data.message);
}

// 删除
async function onDelete (id) {
    const res = await request({
        url: API.ARTICLE_DELETE,
        method: 'delete',
        params: {
            id,
        },
    });
    // layer.msg(res.data.message);
    // 删完 查询
    search();
}

window.onEdit = onEdit;
window.onDelete = onDelete;

async function search () {
    const res = await request({
        url: API.ARTICLE_CATES,
    });
    data = res.data.data;
    $('tbody').html(data.map(d => `
        <tr>
            <td>${d.id}</td>
            <td>${d.cate_name}</td>
            <td>${d.cate_alias}</td>
            <td>
                <button onclick="onEdit(${d.id})" type="button" class="layui-btn layui-btn-xs">修改</button>
                <button onclick="onDelete(${d.id})" type="button" class="layui-btn layui-btn-danger layui-btn-xs">删除</button>
            </td>
        </tr>
    `).join(''));
}

search();

layui.use('form', function(){
    const { form } = layui;

    //监听提交
    form.on('submit(ok)', function (data) {
        const params = data.field;
        // 拿params发请求
        (async () => {
            switch (status) {
                case 'add':
                    await onAddOk(params);
                    break;
                case 'edit':
                    await onEditOk(params);
                    break;

                default:
                    break;
            }
            // 不管是添加还是修改 都得刷新
            search();
        })();
        // 关闭弹窗
        layer.close(layerId);

        return false;
    });
});

// 点击弹出添加弹出层
$('#add').on('click', () => {
    status = 'add';
    // 打开之前先清空input
    $('#name').val('');
    $('#alias').val('');
    // 打开
    layerId = layer.open({
        type: 1,
        title: '添加文章分类',
        content: $('.popup'),
        cancel () {
            setTimeout(() => {
                $('.popup').hide();
            });
        },
    });
});